<?php

namespace maotool\core\text\password;

use maotool\core\text\password\result\PasswdStrengthError;
use maotool\core\text\password\result\PasswdStrengthSuccess;

/**
 * 检测密码强度
 */
class PasswdStrength
{

    /**
     * @var PasswdStrengthRule[]
     */
    protected $passwdStrengthRules;

    public function __construct(PasswdStrengthRule ...$passwdStrengthRule)
    {
        $this->passwdStrengthRules = $passwdStrengthRule;
    }

    public static function rules(PasswdStrengthRule ...$passwdStrengthRule)
    {
        return new self(...$passwdStrengthRule);
    }

    function preCheck()
    {
        return $this->check(null);
    }

    function total()
    {
        return count($this->passwdStrengthRules);
    }

    function check($password)
    {
        $data = new PasswdStrengthData();
        $data->results = [];
        $data->successResults = [];
        $data->errorResults = [];
        foreach ($this->passwdStrengthRules as $passwdStrengthRule) {
            $result = $passwdStrengthRule->handle($password);
            if ($result instanceof PasswdStrengthError) {
                $data->errorResults[] = $result;
            } else if ($result instanceof PasswdStrengthSuccess) {
                $data->successResults[] = $result;
            }
            $data->results[] = $result;
        }
        $data->total = $this->total();
        $data->index = $data->total - count($data->errorResults);
        $data->progress = (($data->total - count($data->errorResults)) / $data->total) * 100;
        $data->isSuccess = count($data->errorResults) == 0;
        $data->isError = count($data->errorResults) > 0;
        $data->firstErrorResult = $data->isError ? $data->errorResults[0] : null;
        return $data;
    }

}